<script setup lang="ts">
import { useRouter } from 'vue-router';
import CarPopup from '@/pages/car/carPopup.vue';
import {
  batchDelCartPost,
  cartGet,
  delCartPost,
  goodsDetailGet,
  updateCarPost,
  updateCheckedPost,
} from '@/services/goods.ts';
import type { CarList, ApparatusCategory, ExpandparamValueList, ComboItemList } from '@/types';

const $router = useRouter();
const carList = ref<CarList[]>([]);
const totals = computed(() => {
  return carList.value.reduce(
    (total, item) => {
      const checkItems = item.cartItemList.filter((e) => e.isChecked === true);
      let carNum = (total.carNum += item.cartItemList.length);
      let totalPrice = (total.totalPrice += checkItems.reduce(
        (d, e) => d + e.currentPrice * e.amount,
        0,
      ));
      return { carNum, totalPrice };
    },
    { carNum: 0, totalPrice: 0 },
  );
});
const onStepChange = async (props: any) => {
  // 弹窗关闭之后这个函数也会执行一次 因为数量发生了改变
  const { err } = await updateCarPost({
    amount: props.amount,
    cartItemId: props.cartItemId,
  });
  if (err) {
    showToast(err);
    return;
  }
};

// 编辑
const editCar = ref(false);
const onEditClick = () => {
  editCar.value = !editCar.value;
  carList.value = carList.value.map((item: any) => {
    const updateCartItem = (cartItem: any) => {
      if (!editCar.value) {
        // 结算状态：下架或删除的商品自动取消选中
        const isInvalidItem = cartItem.goodsStatus === 'PUTOFF' || cartItem.delFlag === 'YES';
        return {
          ...cartItem,
          isChecked: isInvalidItem ? false : cartItem.isChecked,
        };
      }
      // 编辑状态：如果父项被选中，则子项强制选中
      return {
        ...cartItem,
        isChecked: item.isChecked || cartItem.isChecked,
      };
    };
    return {
      ...item,
      cartItemList: item.cartItemList.map(updateCartItem),
    };
  });
};

// 选中的逻辑：店铺有效商品全选中 --> 当前店铺选中; 所有店铺全选中（当前店铺全是失效商品 当前店铺全选失效） --> 全选选中
const isCheckAll = ref(false);
const checkChange = () => {
  // 所有有效商品
  const allCheckedItems = carList.value
    .flatMap((item) => item.cartItemList)
    .filter((cartItem) => {
      return cartItem.goodsStatus !== 'PUTOFF' && cartItem.delFlag !== 'YES';
    });
  // 所有选中商品
  const allReasonItems = carList.value
    .flatMap((item) => item.cartItemList)
    .filter((cartItem) => {
      return cartItem.goodsStatus !== 'PUTOFF' && cartItem.delFlag !== 'YES' && cartItem.isChecked;
    });
  return allCheckedItems.length === allReasonItems.length;
};
const onCheckAllChange = async () => {
  carList.value = carList.value.map((item: any) => {
    return {
      ...item,
      isChecked: item.cartItemList.every(
        (carItem: any) =>
          (carItem.goodsStatus === 'PUTOFF' || carItem.delFlag === 'YES') && !editCar.value,
      )
        ? false
        : isCheckAll.value,
      cartItemList: item.cartItemList.map((cartItem: any) => {
        return {
          ...cartItem,
          isChecked:
            (cartItem.goodsStatus === 'PUTOFF' || cartItem.delFlag === 'YES') && !editCar.value
              ? false
              : isCheckAll.value,
        };
      }),
    };
  });

  // 处理选中请求
  const cartItemIds: string[] = [];
  carList.value.forEach((item) => {
    item.cartItemList.forEach((car) => {
      if (car.goodsStatus !== 'PUTOFF' && car.delFlag !== 'YES') {
        cartItemIds.push(car.cartItemId); // cartItemId
      }
    });
  });
  const { err } = await updateCheckedPost({
    cartItemIds: [...cartItemIds],
    checked: isCheckAll.value,
  });
  if (err) {
    showToast(err);
    return;
  }
};
const onCheckShopClick = async (props: any) => {
  const isDisable = props.cartItemList.every(
    (item: any) => (item.goodsStatus === 'PUTOFF' || item.delFlag === 'YES') && !editCar.value,
  );
  if (isDisable && !editCar.value) {
    props.isChecked = false;
    return;
  }
  carList.value = carList.value.map((item: any) => {
    if (item.id === props.id) {
      return {
        ...item,
        cartItemList: item.cartItemList.map((cartItem: any) => {
          return {
            ...cartItem,
            isChecked:
              (cartItem.goodsStatus === 'PUTOFF' || cartItem.delFlag === 'YES') && !editCar.value
                ? false
                : props.isChecked,
          };
        }),
      };
    }
    return item;
  });
  const cartItemIds = props.cartItemList
    .filter((item: any) => item.goodsStatus !== 'PUTOFF' && item.delFlag !== 'YES')
    .map((car: any) => {
      return car.cartItemId;
    });
  const { err } = await updateCheckedPost({
    cartItemIds: [...cartItemIds],
    checked: props.isChecked,
  });
  if (err) {
    showToast(err);
    return;
  }
  isCheckAll.value = checkChange();
};
const onCheckOneClick = async (props: any, car: any) => {
  carList.value = carList.value.map((item: any) => {
    if (item.id === props.id) {
      return {
        ...item,
        isChecked: item.cartItemList.every(
          (cartItem: any) =>
            cartItem.isChecked ||
            ((cartItem.goodsStatus === 'PUTOFF' || cartItem.delFlag === 'YES') && !editCar.value),
        ),
      };
    }
    return item;
  });
  if (car.goodsStatus !== 'PUTOFF' && car.delFlag !== 'YES') {
    const { err } = await updateCheckedPost({
      cartItemIds: [car.cartItemId],
      checked: car.isChecked,
    });
    if (err) {
      showToast(err);
      return;
    }
  }
  isCheckAll.value = checkChange();
};

// 提交 订单
const loading = ref(false);
const onSubmit = () => {
  showToast('点击按钮');
  loading.value = true;
};

const onSettlementClick = () => {
  if (carList.value.length === 0) {
    showToast('购物车为空');
    return;
  }
  const findCheck = carList.value.some((item: any) => {
    return item.cartItemList.some((car: any) => {
      return car.isChecked;
    });
  });
  if (!findCheck) {
    showToast('请选择商品');
    return;
  }
  $router.push({ path: '/settlement' });
};

const onImageClick = (props: any) => {
  if (props.goodsStatus === 'PUTOFF' || props.delFlag === 'YES') {
    showToast('商品失效');
    return;
  }
  $router.push({
    path: `/goodsDetails/${props.goodsId}`,
  });
};
// 删除
const onDelMoreClick = async () => {
  if (carList.value.length === 0) {
    showToast('购物车为空');
    return;
  }
  const delItems = carList.value
    .flatMap((item) => item.cartItemList)
    .filter((carItem) => carItem.isChecked)
    .map((carItem) => {
      return carItem.cartItemId;
    });
  let { err } = await batchDelCartPost(delItems);
  if (err) {
    showToast(err);
  } else {
    showToast('删除成功');
    await loadData();
  }
};
const onDelClick = async (car: any) => {
  let { err } = await delCartPost({
    cartItemId: car.cartItemId,
  });
  if (err) {
    showToast(err);
  } else {
    showToast('删除成功');
    await loadData();
  }
};

// 弹窗
const showPopup = ref(false);
let popupList = reactive({
  goodsName: '',
  goodsImg: '',
  goodsSalesPrice: 0,
  goodsExpandparamValueList: [] as ExpandparamValueList[],
  apparatusCategory: {} as ApparatusCategory,
  minimumQuantity: 1,
  amount: 1,
  cartItemId: '',
  isCombo: '',
  comboItemList: [] as ComboItemList[],
});

const onSvgClick = async (props: any) => {
  if (props.goodsStatus === 'PUTOFF' || props.delFlag === 'YES') {
    showToast('商品失效');
    return;
  }
  const { err, data } = await goodsDetailGet(props.goodsId);
  if (err) {
    showToast(err);
    return;
  }
  popupList = data.goodsVo;
  console.log('popupList', popupList);
  popupList.amount = props.amount;
  popupList.cartItemId = props.cartItemId;
  showPopup.value = true;
};

const loadData = async () => {
  const { data, err } = await cartGet();
  if (err) {
    showToast(err);
    return;
  }
  // 统一处理选中的情况
  carList.value = data.list.map((item: any) => {
    // 有效商品
    const filterList = item.cartItemList.filter((carItem: any) => {
      return carItem.goodsStatus !== 'PUTOFF' && carItem.delFlag !== 'YES';
    });
    return {
      ...item,
      isChecked:
        filterList.length === 0
          ? false
          : filterList.every((carItem: any) => carItem.checked === 'YES'),
      cartItemList: item.cartItemList.map((cartItem: any) => {
        return {
          ...cartItem,
          isChecked:
            cartItem.checked === 'YES' &&
            cartItem.goodsStatus !== 'PUTOFF' &&
            cartItem.delFlag !== 'YES',
        };
      }),
    };
  });
  isCheckAll.value = checkChange();
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="car-container">
    <div class="car_top">
      <div class="top_title">购物车（{{ totals.carNum }}）</div>
      <div v-show="totals.carNum !== 0" class="top_edit" @click="onEditClick">
        {{ editCar ? '完成' : '编辑' }}
      </div>
    </div>
    <div class="shop_box" v-for="item in carList" :key="item.id">
      <div class="goods_top">
        <div class="goods_check">
          <van-checkbox @click="onCheckShopClick(item)" v-model="item.isChecked"></van-checkbox>
        </div>
        <svg-icon icon-class="shop" size="1.4em" />
        <div class="goods_company">{{ item.supplierName }}</div>
      </div>
      <van-swipe-cell v-for="car in item.cartItemList" :key="car.id">
        <div class="goods_box">
          <div>
            <van-checkbox
              v-model="car.isChecked"
              @click="onCheckOneClick(item, car)"
              :disabled="(car.goodsStatus === 'PUTOFF' || car.delFlag === 'YES') && !editCar"
            ></van-checkbox>
          </div>
          <div class="right">
            <van-image @click="onImageClick(car)" :src="car.goodsImg?.split(',')[0]" round />
            <div class="posText" v-if="car.goodsStatus === 'PUTOFF' || car.delFlag === 'YES'">
              商品失效
            </div>
            <div class="right_spc">
              <van-text-ellipsis :content="car.goodsName" />
              <div class="spc_text_bottom" @click="onSvgClick(car)">
                <div class="spc_title">
                  <van-text-ellipsis :content="car.goodsSpec" />
                </div>
                <svg-icon icon-class="right" size="1.2em" />
              </div>
              <div class="right_price">
                <div class="goods_price">
                  <span>￥</span>
                  <span class="price_num">{{ car.currentPrice }}</span>
                </div>
                <van-stepper
                  :disabled="car.goodsStatus === 'PUTOFF' || car.delFlag === 'YES'"
                  @change="onStepChange(car)"
                  :min="car.minimumQuantity"
                  v-model="car.amount"
                  integer
                />
              </div>
            </div>
          </div>
        </div>
        <template #right>
          <van-button
            @click="onDelClick(car)"
            square
            text="删除"
            type="danger"
            style="height: 100%"
          />
        </template>
      </van-swipe-cell>
    </div>
    <van-empty v-show="carList.length === 0" description="购物车内暂无商品" />
    <div class="car_footer"></div>
  </div>
  <van-submit-bar v-if="editCar">
    <van-checkbox v-model="isCheckAll" @click="onCheckAllChange"> 全选</van-checkbox>
    <template #button>
      <div class="cleanButton">
        <van-button plain type="primary" @click="onDelMoreClick">删除</van-button>
      </div>
    </template>
  </van-submit-bar>
  <van-submit-bar :loading="loading" @submit="onSubmit" button-color="#E89000" v-else>
    <van-checkbox v-show="totals.carNum !== 0" v-model="isCheckAll" @click="onCheckAllChange">
      全选
    </van-checkbox>
    <!--  这个元素只是占位 当购物车为空 隐藏全选按钮  -->
    <div></div>
    <template #button>
      <div class="setButton">
        <div class="total_Price">
          <div class="total_title">合计：</div>
          <div class="total_price">
            <div>￥</div>
            <div class="total_text">{{ totals.totalPrice.toFixed(2) }}</div>
          </div>
        </div>
        <van-button plain type="primary" @click="onSettlementClick">结算</van-button>
      </div>
    </template>
  </van-submit-bar>
  <van-popup
    v-model:show="showPopup"
    :style="{ maxHeight: '60%' }"
    safe-area-inset-bottom
    position="bottom"
    :destroy-on-close="true"
  >
    <CarPopup v-model="showPopup" @load-Data="loadData" :popupList="popupList"></CarPopup>
  </van-popup>
</template>

<style lang="scss" scoped>
.car-container {
  background: #f6f6f6;
  min-height: calc(100vh - 50px);

  .car_top {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white;
    padding: 0 16px;

    .top_title {
      font-size: 14px;
      font-weight: 500;
      color: #222222;
    }

    .top_edit {
      color: #787878;
      font-size: 13px;
    }
  }

  .shop_box {
    width: 100%;
    height: 100%;
    margin-bottom: 4px;
    background: white;

    .goods_check {
      margin-right: 8px;
    }

    .goods_top {
      width: 100%;
      height: 40px;
      padding-left: 20px;
      display: flex;
      align-items: center;

      .goods_company {
        font-size: 14px;
        font-weight: 500;
        margin-left: 8px;
        color: #222222;
      }
    }

    .goods_box {
      width: 100%;
      height: 96px;
      padding-left: 20px;
      display: flex;
      align-items: center;

      .right {
        display: flex;
        position: relative;
        padding-right: 16px;

        .van-image {
          width: 88px;
          height: 88px;
          margin: 0 8px;
          border-radius: 8px;
        }

        .posText {
          width: 88px;
          height: 20px;
          font-size: 12px;
          font-weight: 400;
          background-color: rgba(0, 0, 0, 0.6); /* 黑色，50%透明度 */
          color: #ffffff;
          position: absolute;
          bottom: 0;
          left: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0 0 10px 10px;
        }

        .right_spc {
          width: 219px;
          height: 88px;

          .van-text-ellipsis {
            color: #000000;
            font-size: 14px;
            font-weight: 500;
          }

          .spc_text_bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .spc_title {
              width: 190px;
            }

            .van-text-ellipsis {
              color: #787878;
              font-size: 13px;
              font-weight: 400;
            }
          }

          .right_price {
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .goods_price {
              font-size: 12px;
              color: #e86600;
              font-weight: 400;

              .price_num {
                font-size: 16px;
                font-weight: 500;
              }
            }
          }
        }
      }
    }
  }
}

.setButton {
  display: flex;
  align-items: center;
  justify-content: center;

  .total_Price {
    height: 24px;
    margin-right: 8px;
    display: flex;
    align-items: center;

    .total_title {
      font-size: 12px;
      font-weight: 400;
      color: #454545;
    }

    .total_price {
      display: flex;
      align-items: center;
      font-size: 12px;
      font-weight: 400;
      color: #e86600;

      .total_text {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  :deep(.van-button) {
    width: 90px;
    height: 42px;
    color: #fff;
    background: #e89000;
    border: 1px solid #e89000;
  }
}

.car_footer {
  background: #f6f6f6;
  height: 50px;
  width: 100%;
}

:deep(.van-submit-bar__bar) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.van-submit-bar {
  position: fixed;
  bottom: 50px;
  left: 0;
}

:deep(.van-empty) {
  background: white;
}

:deep(.van-submit-bar__bar) {
  border-bottom: 1px solid #f6f6f6;
}

:deep(.van-stepper__minus) {
  width: 20px;
  height: 20px;
  color: #787878;
  background: transparent;
}

:deep(.van-stepper__plus) {
  width: 20px;
  height: 20px;
  color: #787878;
  background: transparent;
}

:deep(.van-stepper__input) {
  width: 29px;
  height: 18px;
  border-radius: 4px;
  background: #ebebeb;
}

.cleanButton {
  :deep(.van-button) {
    width: 90px;
    height: 42px;
    color: #e89000;
    border: 1px solid #e89000;
  }
}

.van-empty {
  background: #f6f6f6;
}
</style>
